<template>
  <div>
    <a-modal
      :title="title"
      :width="1000"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @cancel="handleCancel"
      :destroyOnClose="true"
      :class="'jee-outer-modal'"
    >
      <a-spin :spinning="confirmLoading">
        <!-- 新格尔优化软件内容 -->
        <template v-if="orderInfo.optimizationSoftwareType == 1">
          <!-- 使用标签页切换型材清单和配件清单 -->
          <a-tabs defaultActiveKey="1">
            <a-tab-pane key="1" tab="型材清单">
              <!-- 型材清单表格 -->
              <a-table
                ref="table"
                size="middle"
                bordered
                rowKey="id"
                :columns="columns"
                :dataSource="profileMaterials"
                :pagination="{ pageSize: 10 }"
                :scroll="{ y: 300, x: 1000 }"
              >
                <template slot="action" slot-scope="text, record">
                  <a @click="showCutDetails(record)"> <a-icon type="eye" /> 切割方案 </a>
                </template>
              </a-table>
            </a-tab-pane>

            <a-tab-pane key="2" tab="配件清单">
              <!-- 配件清单表格 -->
              <a-table
                ref="accessoriesTable"
                size="middle"
                bordered
                rowKey="id"
                :columns="accessoriesColumns"
                :dataSource="accessories"
                :pagination="{ pageSize: 10 }"
                :scroll="{ y: 300, x: 800 }"
              >
              </a-table>
            </a-tab-pane>
          </a-tabs>
        </template>

        <!-- 长风优化软件内容 -->
        <template v-else>
          <!-- 使用标签页切换型材清单和配件清单 -->
          <a-tabs defaultActiveKey="1">
            <a-tab-pane key="1" tab="型材清单">
              <!-- 长风型材清单表格 -->
              <a-table
                ref="cfMaterialTable"
                size="middle"
                bordered
                rowKey="id"
                :columns="cfMaterialColumns"
                :dataSource="profileMaterials"
                :pagination="{ pageSize: 10 }"
                :scroll="{ y: 300, x: 1200 }"
              >
                <template slot="action" slot-scope="text, record">
                  <a @click="showCfCutDetails(record)"> <a-icon type="eye" /> 切割详情 </a>
                </template>
              </a-table>
            </a-tab-pane>

            <a-tab-pane key="2" tab="配件清单">
              <!-- 长风配件清单表格 -->
              <a-table
                ref="cfAccessoriesTable"
                size="middle"
                bordered
                rowKey="id"
                :columns="cfAccessoriesColumns"
                :dataSource="accessories"
                :pagination="{ pageSize: 10 }"
                :scroll="{ y: 300, x: 800 }"
              >
              </a-table>
            </a-tab-pane>
          </a-tabs>
        </template>
      </a-spin>

      <!-- 添加底部按钮区域 -->
      <template slot="footer">
        <a-button key="back" @click="handleCancel">取消</a-button>
        <a-button key="submit" type="primary" :loading="submitLoading" @click="submitOrder">提交审核</a-button>
      </template>

      <!-- 切割方案详情模态框 -->
      <a-modal
        title="切割方案详情"
        :width="900"
        :visible="cutDetailsVisible"
        :footer="null"
        @cancel="() => (cutDetailsVisible = false)"
        :destroyOnClose="true"
        :class="'jee-outer-modal'"
      >
        <a-spin :spinning="detailsLoading">
          <div class="cut-details-header">
            <p><strong>型材编号：</strong>{{ currentProfileMaterial ? currentProfileMaterial.profileCode : '' }}</p>
            <p><strong>型材名称：</strong>{{ currentProfileMaterial ? currentProfileMaterial.profileName : '' }}</p>
            <p><strong>颜色：</strong>{{ currentProfileMaterial ? currentProfileMaterial.color : '' }}</p>
          </div>

          <a-table
            ref="cutDetailsTable"
            size="middle"
            bordered
            rowKey="id"
            :columns="cutDetailsColumns"
            :dataSource="cutDetails"
            :pagination="{ pageSize: 10 }"
            :scroll="{ x: 900 }"
          >
            <!-- 切割方案列 -->
            <template slot="cutSchemeSlot" slot-scope="text">
              <div style="word-break: break-all; white-space: pre-line">{{ text }}</div>
            </template>

            <!-- 优化率列 -->
            <template slot="optimizationRateSlot" slot-scope="text">
              {{ text ? (text * 100).toFixed(2) + '%' : '' }}
            </template>
          </a-table>
        </a-spin>
      </a-modal>

      <!-- 长风切割详情模态框 -->
      <a-modal
        title="长风切割详情"
        :width="900"
        :visible="cfCutDetailsVisible"
        :footer="null"
        @cancel="() => (cfCutDetailsVisible = false)"
        :destroyOnClose="true"
        :class="'jee-outer-modal'"
      >
        <a-spin :spinning="detailsLoading">
          <div class="cut-details-header">
            <p><strong>型材编号：</strong>{{ currentProfileMaterial ? currentProfileMaterial.profileCode : '' }}</p>
            <p><strong>型材名称：</strong>{{ currentProfileMaterial ? currentProfileMaterial.profileName : '' }}</p>
            <p><strong>颜色：</strong>{{ currentProfileMaterial ? currentProfileMaterial.color : '' }}</p>
          </div>

          <a-table
            ref="cfCutDetailsTable"
            size="middle"
            bordered
            rowKey="id"
            :columns="cfCutDetailsColumns"
            :dataSource="cfCutDetails"
            :pagination="{ pageSize: 10 }"
            :scroll="{ x: 900 }"
          >
            <!-- 切割方案列 -->
            <template slot="cutSchemeSlot" slot-scope="text">
              <div style="word-break: break-all; white-space: pre-line">{{ text }}</div>
            </template>

            <!-- 操作列 -->
            <template slot="actionSlot" slot-scope="text, record">
              <a @click="showWorkDetails(record)"> <a-icon type="tool" /> 加工方案 </a>
            </template>
          </a-table>
        </a-spin>
      </a-modal>

      <!-- 加工方案详情模态框 -->
      <a-modal
        title="加工方案详情"
        :width="900"
        :visible="workDetailsVisible"
        :footer="null"
        @cancel="() => (workDetailsVisible = false)"
        :destroyOnClose="true"
        :class="'jee-outer-modal'"
      >
        <a-spin :spinning="workDetailsLoading">
          <div class="cut-details-header">
            <p><strong>编码：</strong>{{ currentCutDetail ? currentCutDetail.barCode : '' }}</p>
            <p><strong>长度：</strong>{{ currentCutDetail ? currentCutDetail.length + 'mm' : '' }}</p>
            <p><strong>窗号：</strong>{{ currentCutDetail ? currentCutDetail.windowNo : '' }}</p>
          </div>

          <a-table
            ref="workDetailsTable"
            size="middle"
            bordered
            rowKey="id"
            :columns="workDetailsColumns"
            :dataSource="workDetails"
            :pagination="{ pageSize: 10 }"
            :scroll="{ x: 600 }"
          >
          </a-table>
        </a-spin>
      </a-modal>
    </a-modal>
  </div>
</template>

<script>
import { getCutDetails, getOrderMaterialsAndAccessories } from '@/api/oms/designFile'
import { postAction, getAction } from '@/api/manage'

export default {
  name: 'SubmitReviewModal',
  props: {
    // 订单ID
    orderId: {
      type: String,
      required: true,
      default: '',
    },
  },
  data() {
    return {
      title: '提交审核',
      visible: false,
      confirmLoading: false,
      submitLoading: false,
      optimizeSoftType: 0, // 默认为长风
      orderInfo: {}, // 添加订单信息对象
      profileMaterials: [],
      accessories: [],
      columns: [
        {
          title: '型材编号',
          dataIndex: 'profileCode',
          width: 120,
        },
        {
          title: '型材名称',
          dataIndex: 'profileName',
          width: 120,
        },
        {
          title: '颜色',
          dataIndex: 'color',
          width: 100,
        },
        {
          title: '长度(mm)',
          dataIndex: 'length',
          width: 100,
        },
        {
          title: '数量(根)',
          dataIndex: 'quantity',
          width: 100,
        },
        {
          title: '重量(kg)',
          dataIndex: 'weight',
          width: 100,
        },
        {
          title: '备注',
          dataIndex: 'remark',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 100,
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 配件清单表格列配置
      accessoriesColumns: [
        {
          title: '窗号',
          dataIndex: 'windowNo',
          width: 100,
        },
        {
          title: '配件编号',
          dataIndex: 'accessoryCode',
          width: 120,
        },
        {
          title: '配件名称',
          dataIndex: 'accessoryName',
          width: 120,
        },
        {
          title: '规格',
          dataIndex: 'specification',
          width: 120,
        },
        {
          title: '长度/数量',
          dataIndex: 'lengthQuantity',
          width: 80,
        },
      ],
      // 切割方案详情相关
      cutDetailsVisible: false,
      detailsLoading: false,
      currentProfileMaterial: null,
      cutDetails: [],
      cutDetailsColumns: [
        {
          title: '序号',
          dataIndex: 'serialNo',
          width: 80,
        },
        {
          title: '长度(mm)',
          dataIndex: 'length',
          width: 100,
        },
        {
          title: '数量(根)',
          dataIndex: 'quantity',
          width: 100,
        },
        {
          title: '切割方案',
          dataIndex: 'cutScheme',
          scopedSlots: { customRender: 'cutSchemeSlot' },
        },
        {
          title: '锯向',
          dataIndex: 'cutDirection',
          width: 100,
        },
        {
          title: '优化率',
          dataIndex: 'optimizationRate',
          width: 100,
          scopedSlots: { customRender: 'optimizationRateSlot' },
        },
        {
          title: '余料(mm)',
          dataIndex: 'remnant',
          width: 100,
        },
      ],
      // API URL
      url: {
        getCurrentUserOptimizeSoftType: '/sys/employee/getCurrentUserOptimizeSoftType',
        submitForReview: '/oms/designFile/submitForReview',
        queryById: '/oms/productSalesOrder/queryById',
      },
      // 长风优化软件相关
      cfMaterialColumns: [
        {
          title: '型材编号',
          dataIndex: 'profileCode',
          width: 120,
          fixed: 'left',
        },
        {
          title: '型材名称',
          dataIndex: 'profileName',
          width: 120,
        },
        {
          title: '颜色',
          dataIndex: 'color',
          width: 100,
        },
        {
          title: '长度(mm)',
          dataIndex: 'length',
          width: 100,
        },
        {
          title: '宽度(mm)',
          dataIndex: 'width',
          width: 100,
        },
        {
          title: '高度(mm)',
          dataIndex: 'height',
          width: 100,
        },
        {
          title: '数量(根)',
          dataIndex: 'quantity',
          width: 100,
        },
        {
          title: '重量(kg)',
          dataIndex: 'weight',
          width: 100,
        },
        {
          title: '备注',
          dataIndex: 'remark',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 100,
          fixed: 'right',
          scopedSlots: { customRender: 'action' },
        },
      ],
      cfAccessoriesColumns: [
        {
          title: '配件编号',
          dataIndex: 'accessoryCode',
          width: 120,
        },
        {
          title: '配件名称',
          dataIndex: 'accessoryName',
          width: 120,
        },
        {
          title: '规格',
          dataIndex: 'specification',
          width: 120,
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: 80,
        },
        {
          title: '单位',
          dataIndex: 'unit',
          width: 80,
        },
        {
          title: '品牌',
          dataIndex: 'brand',
          width: 80,
        },
      ],
      // 长风切割详情相关
      cfCutDetailsVisible: false,
      cfCutDetails: [],
      cfCutDetailsColumns: [
        {
          title: '序号',
          dataIndex: 'serialNo',
          width: 80,
        },
        {
          title: '切割长度(mm)',
          dataIndex: 'length',
          width: 100,
        },
        {
          title: '编码',
          dataIndex: 'barCode',
          width: 120,
        },
        {
          title: '位置',
          dataIndex: 'position',
          width: 100,
        },
        {
          title: '窗号',
          dataIndex: 'windowNo',
          width: 100,
        },
        {
          title: '切割方案',
          dataIndex: 'cutScheme',
          scopedSlots: { customRender: 'cutSchemeSlot' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 100,
          scopedSlots: { customRender: 'actionSlot' },
        },
      ],
      // 加工方案相关
      workDetailsVisible: false,
      workDetailsLoading: false,
      currentCutDetail: null,
      workDetails: [],
      workDetailsColumns: [
        {
          title: '序号',
          dataIndex: 'serialNo',
          width: 60,
        },
        {
          title: '加工名称',
          dataIndex: 'workName',
          width: 120,
        },
        {
          title: '位置',
          dataIndex: 'position',
          width: 180,
        },
        {
          title: '窗号',
          dataIndex: 'windowNo',
          width: 80,
        },
        {
          title: '编码',
          dataIndex: 'barCode',
          width: 120,
        },
      ],
    }
  },
  methods: {
    // 显示模态框
    show() {
      this.visible = true
      this.confirmLoading = true

      // 获取订单信息
      this.getOrderInfo()
        .then(() => {
          // 加载型材清单和配件清单
          return this.loadMaterialsAndAccessories()
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },

    // 获取订单信息
    getOrderInfo() {
      return getAction(`/oms/productSalesOrder/queryById?id=${this.orderId}`)
        .then((res) => {
          if (res.success) {
            console.log('获取订单信息成功:', res.result)
            this.orderInfo = res.result || {}
            // 如果订单信息中没有优化软件类型，则使用默认值
            if (this.orderInfo.optimizationSoftwareType === undefined) {
              this.orderInfo.optimizationSoftwareType = 0 // 默认为长风
            }
          } else {
            console.error('获取订单信息失败:', res.message)
            this.$message.warning('获取订单信息失败: ' + (res.message || '未知错误'))
            this.orderInfo = { optimizationSoftwareType: 0 } // 默认为长风
          }
        })
        .catch((err) => {
          console.error('获取订单信息异常:', err)
          this.$message.warning('获取订单信息异常，使用默认值')
          this.orderInfo = { optimizationSoftwareType: 0 } // 默认为长风
        })
    },

    // 获取当前用户的优化软件类型 - 保留此方法但不再使用
    getCurrentUserOptimizeSoftType() {
      return getAction(this.url.getCurrentUserOptimizeSoftType)
        .then((res) => {
          if (res.success) {
            console.log('获取到用户优化软件类型:', res.result)
            this.optimizeSoftType = res.result || 0 // 如果没有返回值，则默认为0
          } else {
            console.error('获取优化软件类型失败:', res.message)
            this.$message.warning('获取优化软件类型信息失败: ' + (res.message || '未知错误'))
            this.optimizeSoftType = 0
          }
        })
        .catch((err) => {
          console.error('获取优化软件类型异常:', err)
          this.$message.warning('获取优化软件类型信息异常，使用默认值')
          this.optimizeSoftType = 0
        })
    },

    // 加载型材清单和配件清单
    loadMaterialsAndAccessories() {
      return getOrderMaterialsAndAccessories(this.orderId)
        .then((res) => {
          if (res.success) {
            console.log('获取型材清单和配件清单成功，数据:', res.result)

            // 判断是否为长风优化软件类型
            if (this.orderInfo.optimizationSoftwareType !== 1) {
              // 长风类型
              // 对长风型材清单进行汇总处理
              const profileMaterialsMap = new Map()
              const originalProfileMaterials = res.result.profileMaterials || []

              // 遍历原始型材数据
              originalProfileMaterials.forEach((item) => {
                // 生成唯一键：型材编号_型材名称_颜色_长度_宽度_高度
                const key = `${item.profileCode}_${item.profileName}_${item.color}_${item.length}_${item.width || ''}_${
                  item.height || ''
                }`

                if (profileMaterialsMap.has(key)) {
                  // 如果已存在相同型材，则累加数量和重量
                  const existingItem = profileMaterialsMap.get(key)
                  existingItem.quantity += item.quantity || 1
                  existingItem.weight += item.weight || 0

                  // 保存原始ID列表，用于后续查询切割详情
                  if (!existingItem.originalIds) {
                    existingItem.originalIds = [existingItem.id]
                  }
                  existingItem.originalIds.push(item.id)
                } else {
                  // 如果不存在，则添加新条目
                  profileMaterialsMap.set(key, { ...item })
                }
              })

              // 转换回数组
              this.profileMaterials = Array.from(profileMaterialsMap.values())
              console.log('汇总后的长风型材清单:', this.profileMaterials)

              // 对长风配件清单进行汇总处理
              const accessoriesMap = new Map()
              const originalAccessories = res.result.accessories || []

              // 遍历原始配件数据
              originalAccessories.forEach((item) => {
                // 生成唯一键：配件编号_配件名称_规格
                const key = `${item.accessoryCode || ''}_${item.accessoryName || ''}_${item.specification || ''}`

                if (accessoriesMap.has(key)) {
                  // 如果已存在相同配件，则累加数量
                  const existingItem = accessoriesMap.get(key)
                  existingItem.quantity = (parseFloat(existingItem.quantity) || 0) + (parseFloat(item.quantity) || 0)
                } else {
                  // 如果不存在，则添加新条目
                  accessoriesMap.set(key, { ...item })
                }
              })

              // 转换回数组
              this.accessories = Array.from(accessoriesMap.values())
              console.log('汇总后的长风配件清单:', this.accessories)
            } else {
              // 新格尔类型，直接使用原始数据
              this.profileMaterials = res.result.profileMaterials || []
              this.accessories = res.result.accessories || []
            }
          } else {
            console.warn('未获取到型材清单和配件清单数据:', res)
            this.$message.warning('未获取到型材清单和配件清单数据')
          }
        })
        .catch((err) => {
          console.error('获取型材清单和配件清单出错', err)
          this.$message.error('获取型材清单和配件清单失败：' + (err.message || '未知错误'))
        })
    },

    // 关闭模态框
    handleCancel() {
      this.visible = false
    },

    // 提交订单
    submitOrder() {
      this.$confirm({
        title: '确认提交',
        content: '确定要提交此订单进行审核吗？提交后将无法再修改。',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          this.submitLoading = true

          // 调用提交审核接口
          // 直接将orderId作为URL参数
          postAction(`${this.url.submitForReview}?orderId=${this.orderId}`, {})
            .then((res) => {
              if (res.success) {
                // 后端updateOrderStatus方法已经记录了进度信息，不需要再次添加
                this.$message.success('订单提交审核成功，等待审核通过')
                this.visible = false
                // 触发刷新列表事件
                this.$emit('submit-success')
              } else {
                this.$message.error(res.message || '提交审核失败')
              }
            })
            .catch((err) => {
              console.error('提交审核出错', err)
              this.$message.error('提交审核失败')
            })
            .finally(() => {
              this.submitLoading = false
            })
        },
      })
    },

    // 显示切割方案详情
    showCutDetails(record) {
      this.currentProfileMaterial = record
      this.cutDetailsVisible = true
      this.loadCutDetails(record)
    },

    // 加载切割方案详情
    loadCutDetails(record) {
      this.detailsLoading = true
      this.cutDetails = []

      getCutDetails(this.orderId, record.profileCode)
        .then((res) => {
          if (res.success) {
            this.cutDetails = res.result || []
          } else {
            this.$message.error(res.message || '获取切割方案详情失败')
          }
        })
        .catch((err) => {
          console.error('获取切割方案详情出错', err)
          this.$message.error('获取切割方案详情失败')
        })
        .finally(() => {
          this.detailsLoading = false
        })
    },

    // 显示长风切割方案详情
    showCfCutDetails(record) {
      this.currentProfileMaterial = record
      this.cfCutDetailsVisible = true
      this.loadCfCutDetails(record)
    },

    // 加载长风切割方案详情
    loadCfCutDetails(record) {
      this.detailsLoading = true
      this.cfCutDetails = []

      // 获取需要查询的ID列表
      const profileIds = record.originalIds || [record.id]

      // 使用Promise.all并行查询所有ID的切割详情
      const promises = profileIds.map((profileId) => {
        return this.$http.get(`/oms/cfProfileCutDetail/getByProfileId?profileId=${profileId}`)
      })

      Promise.all(promises)
        .then((responses) => {
          // 合并所有响应结果
          let allCutDetails = []
          responses.forEach((res) => {
            if (res.success && res.result) {
              allCutDetails = allCutDetails.concat(res.result)
            }
          })

          // 格式化数据以适配表格
          this.cfCutDetails = allCutDetails.map((item, index) => {
            return {
              ...item,
              serialNo: index + 1,
              cutScheme: `左端角度: ${item.sxB}°/${item.sxC}°, 右端角度: ${item.dxB}°/${item.dxC}°`,
            }
          })

          if (this.cfCutDetails.length === 0) {
            this.$message.info('未找到切割详情数据')
          }
        })
        .catch((err) => {
          console.error('获取切割详情出错', err)
          this.$message.error('获取切割详情失败')
        })
        .finally(() => {
          this.detailsLoading = false
        })
    },

    // 显示加工方案详情
    showWorkDetails(record) {
      this.currentCutDetail = record
      this.workDetailsVisible = true
      this.loadWorkDetails(record)
    },

    // 加载加工方案详情
    loadWorkDetails(record) {
      if (!record || !record.barCode) {
        this.$message.warning('无法获取加工方案，缺少编码信息')
        return
      }

      this.workDetailsLoading = true
      this.workDetails = []

      // 获取加工方案详情
      this.$http
        .get(`/oms/cfProfileWorkDetail/getByCutId?cutId=${record.id}`)
        .then((res) => {
          if (res.success) {
            this.workDetails = res.result || []

            // 格式化加工方案数据
            this.workDetails = this.workDetails.map((item, index) => {
              return {
                ...item,
                serialNo: index + 1,
                workScheme: `${item.workName || ''} - ${item.workType || ''}`,
                position: `X:${item.positionX || 0}, Y:${item.positionY || 0}, Z:${item.positionZ || 0}`,
              }
            })

            if (this.workDetails.length === 0) {
              this.$message.info('未找到加工方案数据')
            }
          } else {
            this.$message.error(res.message || '获取加工方案详情失败')
          }
        })
        .catch((err) => {
          console.error('获取加工方案详情出错', err)
          this.$message.error('获取加工方案详情失败')
        })
        .finally(() => {
          this.workDetailsLoading = false
        })
    },
  },
}
</script>

<style scoped>
.cut-details-header {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.cut-details-header p {
  margin-bottom: 5px;
}
</style> 